package com.iRomantic.controller.app;

import java.util.List;

import com.iRomantic.common.AppJsonResponse;
import com.iRomantic.common.BaseController;
import com.iRomantic.common.oss.OSSService;
import com.iRomantic.common.util.FileUtil;
import com.iRomantic.config.Constant;
import com.iRomantic.domain.entity.Bless;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

public class BlessAPPController extends BaseController {

	/**
	 * 发送祝福
	 * @throws Exception 
	 */
	public void send() throws Exception{
		AppJsonResponse jsonResult = this.createAppJsonResponse();
		
		//处理上传图片
		List<UploadFile> files = this.getFiles();
		Bless bless = this.getModel(Bless.class);
		StringBuffer fileNames = new StringBuffer("");
		for(UploadFile file : files){
			String fileName = FileUtil.randomFileName(file.getFileName());
			fileName = iosPictureHandler(fileName);
			OSSService.getInstance().save(Constant.BLESS_PICTURE+bless.getStr("weddingId")+"/"+fileName,file.getFile());
			file.getFile().delete();
			fileNames.append(bless.getStr("weddingId")+"/"+fileName).append(",");
		}
		
		bless.set("messageType", Bless.BLESS_TYPE);
		if(fileNames.length()>0){
			bless.set("pictures", fileNames.substring(0, fileNames.length()-1));//过滤最后的逗号
		}
		if(bless.save()){
			jsonResult.setResult(bless);
			jsonResult.success("发送祝福成功");
		}else{
			jsonResult.setResult(bless);
			jsonResult.failed("发送祝福失败");
		}
		
		renderJson(jsonResult);
	}
	
	/**
	 * 获取 时间搓之前的祝福
	 */
	public void getBefortTimestamp(){
		AppJsonResponse jsonResult = this.createAppJsonResponse();
		Bless bless = this.getModel(Bless.class);
		List<Record> resords = bless.findBeforeTimestampByWedding(bless.getStr("weddingId"), bless.getStr("timeStamp"));
		for(Record r:resords){
			r.set("pictureUrl", Constant.OSS_PATH+Constant.USER_PICTURE+r.get("pictureUrl"));
		}
		jsonResult.setResult(resords);
		jsonResult.success("成功");
		renderJson(jsonResult);
	}
	
	/**
	 * 获取时间搓之后的祝福
	 */
	public void getAfterTimestamp(){
		AppJsonResponse jsonResult = this.createAppJsonResponse();
		Bless bless = this.getModel(Bless.class);
		List<Record> resords = bless.findAfterTimestampByWedding(bless.getStr("weddingId"), bless.getStr("timeStamp"));
		for(Record r:resords){
			r.set("pictureUrl", Constant.OSS_PATH+Constant.USER_PICTURE+r.get("pictureUrl"));
		}
		jsonResult.setResult(resords);
		jsonResult.success("成功");
		renderJson(jsonResult);
	}

}
